from datetime import datetime, tzinfo
from lookas.track.MyTimeZone import MyTimeZone
from lookas.track.Pozycja import Pozycja
from struct import unpack
from pysqlite2 import dbapi2 as sqlite
        
class Explorer:
    trasy = []
        
    def __init__(self, plikOdczyt):
        self.czytajSql(plikOdczyt)
        
    def getTrasy(self):
        return self.trasy

    def setTrasy(self, trasy):
        self.trasy = trasy

    def czytajSql(self, plik):
        connection = sqlite.connect(plik)
        cursor = connection.cursor()
        cursor.execute('SELECT data FROM TRACKS_V1')
        for row in cursor:
            trasa = []
            for x in row:
                if(len(x)%12 == 0):
                    for i in range(len(x)/12):
                        poz = unpack('iii', x[i*12:i*12+12])
                        poz = Pozycja(datetime.fromtimestamp(poz[0], tz=MyTimeZone()), \
                                    float(poz[2])/0x800000, float(poz[1])/0x800000)
                        trasa.append(poz)
            self.trasy.append(trasa)
        connection.close()
        return self.trasy
    
    def zapis(self, nazwa, (content, trac, point)=(0, 0, 0)):

        if point == 0:
            point = '<point date="@lookas:date"><lat>@lookas:lat</lat><lat>@lookas:lon</lat></point>\n'
        if track == 0:
            track = '<track name="@lookas:name">\n@lookas:points</track>\n'
        if content == 0:
            content = '<?xml version="1.0" encoding="UTF-8"?>\n@lookas:track'

        i = 0
        trks = ''
        for trasa in self.trasy:
            i += 1
            pts = ''
            for poz in trasa:
                pt = point.replace("@lookas:date", poz.getCzas().isoformat())
                pt = pt.replace("@lookas:lat", str(poz.getLat()))
                pt = pt.replace("@lookas:lon", str(poz.getLon()))                
                pts += pt + '\n'
            trk = track.replace("@lookas:name", "Trasa_" + str(i))
            trk = trk.replace("@lookas:points", pts)
            trks += trk + '\n'
        doc = content.replace("@lookas:track", trks)
        fwrite = file(nazwa, 'w')
        fwrite.write(doc)
        fwrite.close()
        